﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.HttpContext

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:QuickReply runat=server></{0}:QuickReply>")> _
    Public Class QuickReply
        Inherits ControlsBase
#Region "Protected Members"
        Protected WithEvents tgQR As Controls.Toggle
        Protected WithEvents tgdQR As Controls.ToggleDisplay
        Protected WithEvents plhMessage As PlaceHolder
        Protected WithEvents reqUserName As System.Web.UI.WebControls.RequiredFieldValidator
        Protected WithEvents txtUserName As HtmlControls.HtmlInputText
        Protected WithEvents reqBody As Label
        Protected WithEvents reqSecurityCode As Label
        Protected WithEvents chkSubscribe As CheckBox
        Protected WithEvents ambtnSubmit As Controls.ImageButton
        Protected WithEvents btnSubmit As HtmlControls.HtmlInputButton
        Protected WithEvents trUsername As HtmlControls.HtmlTableRow
        Protected WithEvents trCaptcha As HtmlControls.HtmlTableRow
        Protected WithEvents trSubscribe As HtmlControls.HtmlTableRow

#End Region
#Region "Private Members"
        Private InstanceId As Integer = -1
        Private SiteId As Integer = -1
        Private _Subject As String = String.Empty
#End Region
#Region "Public Properties"
        Public Property Subject() As String
            Get
                Return _Subject
            End Get
            Set(ByVal value As String)
                _Subject = value
            End Set
        End Property
#End Region
#Region "Event Handlers"
        Private Sub QuickReply_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            InstanceId = ControlConfig.InstanceId
            SiteId = ControlConfig.SiteId
            Dim fc As New ForumController
            If forumInfo Is Nothing Then
                ForumInfo = fc.Forums_Get(SiteId, InstanceId, ForumId, Me.UserId, True, False, TopicId)
            End If

            Dim MainSettings As SettingsInfo = DataCache.MainSettings(ControlConfig.InstanceId)
            Dim sTemp As String = String.Empty
            If Not ControlConfig Is Nothing Then
                Dim obj As Object = DataCache.CacheRetrieve(InstanceId & "qr")
                If obj Is Nothing Then
                    sTemp = ParseTemplate()
                Else
                    sTemp = CType(obj, String)
                End If
                sTemp = Utilities.LocalizeControl(sTemp)
                Dim SubscribedChecked As String = String.Empty
                If ControlConfig.User.PrefTopicSubscribe Or Subscriptions.IsSubscribed(SiteId, InstanceId, ForumId, TopicId, SubscriptionTypes.Instant, Me.UserId) Then
                    SubscribedChecked = " checked=true"
                End If
                sTemp = sTemp.Replace("[AF:CONTROL:SUBSCRIBECHECK]", "<input type=""checkbox"" id=""chkSubscribe"" name=""chkSubscribe"" value=""1"" " & SubscribedChecked & """ />")
                'Security
                sTemp = sTemp.Replace("[CREATEROLES]", "1;")
                sTemp = sTemp.Replace("[USERROLES]", ForumUser.UserRoles)
                sTemp = sTemp.Replace("[THEMEPATH]", ThemePath)
                sTemp = sTemp.Replace("[SUBJECT]", Subject)
                sTemp = sTemp.Replace("[REPLYROLES]", ForumInfo.Security.Reply)
                If Not Current.Request.IsAuthenticated Then
                    sTemp = "<%@ Register TagPrefix=""dnn"" Assembly=""DotNetNuke"" Namespace=""DotNetNuke.UI.WebControls""%>" & sTemp
                End If
                If Not sTemp.Contains(Globals.ControlRegisterAFTag) Then
                    sTemp = Globals.ControlRegisterAFTag & sTemp
                End If
                Dim ctl As Control = Page.ParseControl(sTemp)
                LinkControls(ctl.Controls)
                Me.Controls.Add(ctl)
            End If
        End Sub
        Private Sub QuickReply_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                Dim bolShow As Boolean = True
                If Not HttpContext.Current.Request.Cookies("QRShow") Is Nothing Then
                    bolShow = CType(HttpContext.Current.Request.Cookies("QRShow").Value, Boolean)
                End If
                tgdQR.Visible = bolShow
                tgQR.Visible = bolShow
                If Not Current.Request.Browser.IsMobileDevice Then
                    ambtnSubmit.ImageUrl = ThemePath & "save32.png"
                    ambtnSubmit.ImageLocation = "TOP"
                    btnSubmit.Visible = False
                    ambtnSubmit.Visible = True
                    If Not Current.Request.IsAuthenticated Then
                        trSubscribe.Visible = False
                        ambtnSubmit.PostBack = True
                        ambtnSubmit.ClientSideScript = ""
                        reqUserName.Enabled = True
                        reqUserName.Text = "<img src=""" & ThemePath & "warning.png"" />"
                        reqBody.Text = "<img src=""" & ThemePath & "warning.png"" />"
                        reqSecurityCode.Text = "<img src=""" & ThemePath & "warning.png"" />"
                        AddHandler ambtnSubmit.Click, AddressOf ambtnSubmit_Click
                    Else
                        trUsername.Visible = False
                        reqUserName.Visible = False
                        reqUserName.Enabled = False
                        txtUserName.Visible = False
                        trCaptcha.Visible = False


                    End If
                Else
                    btnSubmit.Visible = True
                    ambtnSubmit.Visible = False
                End If
                If Not String.IsNullOrEmpty(Current.Request.Form("txtBody")) And Current.Request.IsAuthenticated And ((Not String.IsNullOrEmpty(Current.Request.Form("hidReply1")) And String.IsNullOrEmpty(Current.Request.Form("hidReply2"))) Or Current.Request.Browser.IsMobileDevice) Then
                    SaveQuickReply()
                End If
            Catch ex As Exception

            End Try

        End Sub
        Private Sub ambtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ambtnSubmit.Click

        End Sub
#End Region
#Region "Private Methods"
        Private Sub SaveQuickReply()
            Dim iFloodInterval As Integer = MainSettings.FloodInterval
            If iFloodInterval > 0 Then
                Dim upc As New UserProfileController
                Dim upi As UserProfileInfo = upc.Profiles_Get(SiteId, InstanceId, Me.UserId)
                If Not upi Is Nothing Then
                    If DateDiff(DateInterval.Second, upi.DateLastPost, Now()) < iFloodInterval Then
                        Dim im As New Controls.InfoMessage
                        im.Message = "<div class=""afmessage"">" & String.Format(Utilities.GetSharedResource("[RESX:Error:FloodControl]"), iFloodInterval) & "</div>"
                        plhMessage.Controls.Add(im)
                        Exit Sub
                    End If
                End If
            End If
            'TODO: Fix for anon
            'If Not Current.Request.IsAuthenticated Then
            '    If Not ctlCaptcha.IsValid Or txtUserName.Value = "" Then
            '        Exit Sub
            '    End If
            'End If
            'Dim ui As New UserProfileInfo
            'If UserId > 0 Then
            '    Dim upc As New UserProfileController
            '    ui = upc.Profiles_Get(PortalId, ForumModuleId, UserId)
            'Else
            '    ui.TopicCount = 0
            '    ui.ReplyCount = 0
            '    ui.RewardPoints = 0
            '    ui.IsMod = False
            '    ui.TrustLevel = -1

            'End If
            Dim fc As New ForumController
            Dim forumInfo As Forum = fc.Forums_Get(SiteId, InstanceId, ForumId, Me.UserId, True, False, TopicId)
            Dim UserIsTrusted As Boolean = False
            UserIsTrusted = Utilities.IsTrusted(forumInfo.DefaultTrustValue, ControlConfig.User.TrustLevel, Permissions.HasPerm(forumInfo.Security.Trust, ForumUser.UserRoles), forumInfo.AutoTrustLevel, ControlConfig.User.PostCount)
            Dim isApproved As Boolean = False
            isApproved = CBool(IIf(ForumInfo.IsModerated = True, False, True))
            If UserIsTrusted Or Permissions.HasPerm(forumInfo.Security.ModApprove, ForumUser.UserRoles) Then
                isApproved = True
            End If
            Dim ri As New ReplyInfo
            Dim db As New Data.Topics
            'im rc As New ReplyController
            Dim ReplyId As Integer = -1
            Dim sUsername As String = String.Empty
            If Current.Request.IsAuthenticated Then
                sUsername = ControlConfig.User.DisplayName
            Else
                sUsername = Utilities.CleanString(SiteId, txtUserName.Value, False, EditorTypes.TEXTBOX, True, False, InstanceId, ThemePath, False)
            End If

            Dim sBody As String = String.Empty
            'TODO: Check for allowhtml
            Dim allowHtml As Boolean = False
            'If forumInfo.AllowHTML Then
            '    allowHtml = isHTMLPermitted(forumInfo.EditorPermittedUsers, IsTrusted, forumInfo.Security.ModEdit)
            'End If
            sBody = Utilities.CleanString(SiteId, Current.Request.Form("txtBody"), allowHtml, EditorTypes.TEXTBOX, forumInfo.UseFilter, forumInfo.AllowScript, InstanceId, ThemePath, forumInfo.AllowEmoticons)
            Dim createDate As Date = Now()
            With ri
                .TopicId = TopicId
                .ReplyToId = TopicId
                .Content.AuthorId = UserId
                .Content.AuthorName = sUsername
                .Content.Body = sBody
                .Content.DateCreated = createDate
                .Content.DateUpdated = createDate
                .Content.IsDeleted = False
                .Content.Subject = Subject
                .Content.Summary = String.Empty
                .IsApproved = isApproved
                .IsDeleted = False
                .Content.IPAddress = Current.Request.UserHostAddress
            End With
            ReplyId = db.Reply_Save(ri)
            'Check if is subscribed
            If Not Current.Request.Params("chkSubscribe") Is Nothing Then
                If Current.Request.Params("chkSubscribe") = "1" And UserId > 0 Then
                    If Not Subscriptions.IsSubscribed(SiteId, InstanceId, ForumId, TopicId, SubscriptionTypes.Instant, UserId) Then
                        'TODO: Fix Subscriptions
                        'Dim sc As New Data.Tracking
                        'sc.Subscription_Update(SiteId, InstanceId, ForumId, TopicId, 1, UserId)
                    End If
                End If
            End If
            If isApproved Then
                'Send Subscriptions
                Try
                    Dim sURL As String = Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
                    Subscriptions.SendSubscriptions(SiteId, InstanceId, PageId, ForumId, TopicId, ReplyId, UserId)
#If SKU <> "LITE" Then
                    Try
                        Dim oSocial As New Social
                        oSocial.AddForumItemToJournal(SiteId, InstanceId, UserId, "forumreply", sURL, Subject, sBody)
                    Catch ex As Exception
                        DotNetNuke.Services.Exceptions.LogException(ex)
                    End Try

#End If
                Catch ex As Exception
                    DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
                End Try
                'Redirect to show post
                Dim fullURL As String = Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
                Current.Response.Redirect(fullURL, False)
            ElseIf isApproved = False Then
                Dim oEmail As New Email
                oEmail.SendEmailToModerators(forumInfo.ModNotifyTemplateId, SiteId, ForumId, ri.TopicId, ReplyId, InstanceId, PageId, String.Empty)
                Dim Params() As String = {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=confirmaction", "afmsg=pendingmod", ParamKeys.TopicId & "=" & TopicId}
                Current.Response.Redirect(Utilities.NavigateUrl(PageId, "", Params), False)
            Else
                Dim fullURL As String = Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
#If SKU <> "LITE" Then
                Try
                    Dim oSocial As New Modules.ActiveForums.Social
                    oSocial.AddForumItemToJournal(SiteId, InstanceId, UserId, "forumreply", fullURL, Subject, sBody)
                Catch ex As Exception
                    DotNetNuke.Services.Exceptions.LogException(ex)
                End Try

#End If
                Current.Response.Redirect(fullURL, False)
            End If

            'End If


        End Sub
        Private Function ParseTemplate() As String
            Dim sOut As String = DisplayTemplate

            DataCache.CacheStore(InstanceId & "qr", sOut)
            Return sOut
        End Function
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                Select Case ctrl.ID
                    Case "tgQR"
                        tgQR = CType(ctrl, Toggle)
                        tgQR.ImagePath = ThemePath
                    Case "tgdQR"
                        tgdQR = CType(ctrl, ToggleDisplay)
                    Case "plhMessage"
                        plhMessage = CType(ctrl, PlaceHolder)
                    Case "reqUserName"
                        reqUserName = CType(ctrl, System.Web.UI.WebControls.RequiredFieldValidator)
                    Case "txtUserName"
                        txtUserName = CType(ctrl, HtmlControls.HtmlInputText)
                    Case "reqBody"
                        reqBody = CType(ctrl, Label)
                    Case "reqSecurityCode"
                        reqSecurityCode = CType(ctrl, Label)
                    Case "chkSubscribe"
                        chkSubscribe = CType(ctrl, CheckBox)
                    Case "ambtnSubmit"
                        ambtnSubmit = CType(ctrl, ImageButton)
                    Case "btnSubmit"
                        btnSubmit = CType(ctrl, HtmlControls.HtmlInputButton)
                    Case "trUsername"
                        trUsername = CType(ctrl, HtmlControls.HtmlTableRow)
                    Case "trCaptcha"
                        trCaptcha = CType(ctrl, HtmlControls.HtmlTableRow)
                    Case "trSubscribe"
                        trSubscribe = CType(ctrl, HtmlControls.HtmlTableRow)
                End Select
                If TypeOf ctrl Is Controls.ControlsBase Then
                    DirectCast(ctrl, Controls.ControlsBase).ControlConfig = Me.ControlConfig
                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
#End Region



    End Class

End Namespace
